//
//  Tools.swift
//  StoreProject
//
//  Created by CYC on 1998/12/29.
//

// UI工具

import UIKit
import CommonCrypto
import Kingfisher

class Tools: NSObject {

    
    
}

// MARK:======================================UIImageView========================================
extension UIImageView {
    
    // MARK:设置普通图片
    func c_image(_ name: String) {
        
        if let image = UIImage.init(named: name) {
            
            self.image = image
        } else {
            self.image = UIImage.init(named: "226")
        }
    }
    
    // MARK:设置网络图片
    func c_webImage(_ url: String, _ placeholder:String = "235") {
        self.kf.setImage(with: URL(string: url), placeholder: UIImage.init(named: placeholder))
    }
}

// MARK:======================================UIButton========================================
extension UIButton {
    
    // 设置点击背景带灰色
    func c_highLight() {
        self.setBackgroundImage(UIImage.init(named: "2"), for: .highlighted)
        self.clipsToBounds = true
    }
    
    // 设置图片
    func c_setImage(_ name: String) {
        self.setImage(UIImage.init(named: name), for: .normal)
    }
    
}

class TextButton: UIButton {
    var text: String?
}

// MARK:======================================UITableView========================================
extension UITableView {
    
    // MARK:设置暂无数据
    @objc func setNoDataAction(list: [Any]) {
        
        // 移除
        for item in self.subviews {
            
            if item.isKind(of: NoDataView.self) {
                
                item.removeFromSuperview()
            }
        }
        
        // 为0则添加
        if list.count == 0 {
            
            let noDataView = NoDataView.init(frame: self.bounds);
            self.addSubview(noDataView)
        }
    }
}


class NoDataView: UIView {
    
    // 暂无数据页
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.creatUIAction()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func creatUIAction() {
        
        self.backgroundColor = .white
        
        let icon = UIImageView.init(frame: CGRect.init(x:(self.c_width() - 68)/2.0, y: (self.c_height() - 68)/2.0 - 50, width: 68, height: 68))
        icon.c_image("3")
        icon.contentMode = .scaleAspectFit
        self.addSubview(icon)
        
        let lab = UILabel.init(frame: CGRect.init(x: 0, y: icon.c_bottom() + 20, width: self.c_width(), height: 20))
        lab.textColor = kLabelColor3
        lab.textAlignment = .center
        lab.font = kRFont(15)
        lab.text = "暂无记录"
        self.addSubview(lab)
    }
}

// MARK:======================================UIView========================================
extension UIView {
    
    func c_left() -> CGFloat {
        return self.frame.origin.x
    }
    
    func c_right() -> CGFloat {
        return self.frame.origin.x + self.frame.size.width
    }
    
    func c_bottom() -> CGFloat {
        return self.frame.origin.y + self.frame.size.height
    }
    
    func c_top() -> CGFloat {
        return self.frame.origin.y
    }
    
    func c_width() -> CGFloat {
        return self.frame.size.width
    }
    
    func c_height() -> CGFloat {
        return self.frame.size.height
    }
    
    func c_centerX() -> CGFloat {
        return self.c_left() + self.c_width() / 2.0
    }
    
    func c_centerY() -> CGFloat {
        return self.c_top() + self.c_height() / 2.0
    }
    
    func c_radius(radius: CGFloat) {
        self.layer.cornerRadius = radius
    }
    
    func c_borderAndRadius(width: CGFloat, color: UIColor, radius: CGFloat) {
        self.layer.cornerRadius = radius
        self.layer.borderColor = color.cgColor
        self.layer.borderWidth = width
    }
    
    func c_shadowAndRadius(scolor:UIColor, offset:CGSize, sradius:CGFloat, sopacity:Float, radius: CGFloat) {
        self.layer.cornerRadius = radius
        self.layer.shadowColor = scolor.cgColor
        self.layer.shadowOffset = offset
        self.layer.shadowRadius = sradius
        self.layer.shadowOpacity = sopacity
    }
    
    func c_topRadius(radius: CGFloat) {
        
        let bez = UIBezierPath.init(roundedRect: self.bounds, byRoundingCorners: [UIRectCorner.topLeft, UIRectCorner.topRight], cornerRadii: CGSize.init(width: radius, height: radius))
        let shape = CAShapeLayer.init()
        shape.frame = self.bounds
        shape.path = bez.cgPath
        self.layer.mask = shape
        
    }
    
    func c_bottomRadius(radius: CGFloat) {
        
        let bez = UIBezierPath.init(roundedRect: self.bounds, byRoundingCorners: [UIRectCorner.bottomLeft, UIRectCorner.bottomRight], cornerRadii: CGSize.init(width: radius, height: radius))
        let shape = CAShapeLayer.init()
        shape.frame = self.bounds
        shape.path = bez.cgPath
        self.layer.mask = shape
        
    }
    
    // 移除所有子视图
    func removeAllSubviews() {
        for v in self.subviews {
            if v.isKind(of: UIView.self) {
                v.removeFromSuperview()
            }
        }
    }
    
}



// MARK:======================================NSString========================================

// 暂不可用
func getPrintString(_ obj: Any) -> String {
    
    var level: String!
    
    
    if let asd = objc_getAssociatedObject(obj, "OBJ_LEVEL") {
        level = String.init(format: "%@", asd as! CVarArg)
    } else {
        level = "0"
    }
    var levelTip: String?
    if level?.nsstring.intValue == 0 {
        levelTip = "\t"
    } else if level.nsstring.intValue == 1 {
        levelTip = "\t\t"
    } else if level.nsstring.intValue == 2 {
        levelTip = "\t\t\t"
    } else if level.nsstring.intValue == 3 {
        levelTip = "\t\t\t\t"
    } else  {
        levelTip = "\t\t\t\t\t"
    }
    let subLevel = String.init(format: "%d", level.nsstring.intValue + 1)
    if obj is [String : Any] {
        
        var string: String?
        let dic = obj as! [String : Any]
        string = "{"
        
        let allKeys = [String](dic.keys)
        let allValues = [Any](dic.values)
        for i in 0 ..< allKeys.count {
            
            
            let thisKey = allKeys[i]
            let thisValue = allValues[i]
            
            objc_setAssociatedObject(thisKey, "OBJ_LEVEL", subLevel, .OBJC_ASSOCIATION_COPY_NONATOMIC);
            objc_setAssociatedObject(thisValue, "OBJ_LEVEL", subLevel, .OBJC_ASSOCIATION_COPY_NONATOMIC);

            string = String.init(format: "%@\n%@%@ = %@", string!, levelTip!, thisKey, getPrintString(thisValue))
            if i != allValues.count - 1 {
                
                string = String.init(format: "%@,", string!)
            }
            
            objc_removeAssociatedObjects(thisKey);
            objc_removeAssociatedObjects(thisValue);
        }
        
        string = String.init(format: "\n%@}", levelTip!)
        return string!
        
    } else if obj is [Any] {
        
        var string: String?
        let array = obj as! [Any]
        string = "["
        
        for i in 0 ..< array.count {
            
            let thisValue = array[i]
            objc_setAssociatedObject(thisValue, "OBJ_LEVEL", subLevel, .OBJC_ASSOCIATION_COPY_NONATOMIC);

            string = String.init(format: "\n%@%@", string!, levelTip!, getPrintString(thisValue))
            if i != array.count - 1 {
                
                string = String.init(format: "%@,", string!)
            }
            
            objc_removeAssociatedObjects(thisValue);
        }
        
        string = String.init(format: "\n%@]", levelTip!)
        return string!
        
    } else {
        return String.init(format: "\"%@\"", obj as! CVarArg)
    }
}

// 判断字符串是否为空
func EmptyText(_ text: String) -> Bool {
    
    if text.isEmpty ||
        text == "" ||
        text == "<null>" ||
        text == "(null)" ||
        text.count == 0 {
        return true
    } else {
        return false
    }
}

extension String {
    
    var nsstring: NSString {
        return NSString.init(string: self)
    }
    
    var doubleValue: Double {
        return self.nsstring.doubleValue
    }
    
    var integerValue: Int {
        return self.nsstring.integerValue
    }
    
    var floatValue: Float {
        return self.nsstring.floatValue
    }
    
    var md5String: String {
        let utf8 = cString(using: .utf8)
        var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
        CC_MD5(utf8, CC_LONG(utf8!.count - 1), &digest)
        return digest.reduce("") { $0 + String(format:"%02x", $1) }
    }
    
    // 返回小数的字符串
    var formatText: String {
        
        var text = String.init(format: "%.6f", self.nsstring.doubleValue)
        
        // 去除尾部多余的内容。如果改了位数，以下内容要做修改
        if text.hasSuffix(".000000") {
            text = text.replacingOccurrences(of: ".000000", with: "")
        } else if text.hasSuffix("00000") {
            text = String.init(format: "%.1f", text.nsstring.doubleValue)
        } else if text.hasSuffix("0000") {
            text = String.init(format: "%.2f", text.nsstring.doubleValue)
        } else if text.hasSuffix("000") {
            text = String.init(format: "%.3f", text.nsstring.doubleValue)
        } else if text.hasSuffix("00") {
            text = String.init(format: "%.4f", text.nsstring.doubleValue)
        } else if text.hasSuffix("0") {
            text = String.init(format: "%.5f", text.nsstring.doubleValue)
        }
        
        return text
    }
    
    // 巨额压缩
    var formatLongText: String {
        
        let amount = self.nsstring.doubleValue
        if amount > 1000 {
            return String.init(format: "%.2fK", amount / 1000.0)
        } else {
            return String.init(format: "%.2f", amount)
        }
    }
    
}

enum CryptoAlgorithm {
    /// 加密的枚举选项
    case MD5, SHA1, SHA224, SHA256, SHA384, SHA512
    
    var HMACAlgorithm: CCHmacAlgorithm {
        var result: Int = 0
        switch self {
        case .MD5:      result = kCCHmacAlgMD5
        case .SHA1:     result = kCCHmacAlgSHA1
        case .SHA224:   result = kCCHmacAlgSHA224
        case .SHA256:   result = kCCHmacAlgSHA256
        case .SHA384:   result = kCCHmacAlgSHA384
        case .SHA512:   result = kCCHmacAlgSHA512
        }
        return CCHmacAlgorithm(result)
    }
    
    var digestLength: Int {
        var result: Int32 = 0
        switch self {
        case .MD5:      result = CC_MD5_DIGEST_LENGTH
        case .SHA1:     result = CC_SHA1_DIGEST_LENGTH
        case .SHA224:   result = CC_SHA224_DIGEST_LENGTH
        case .SHA256:   result = CC_SHA256_DIGEST_LENGTH
        case .SHA384:   result = CC_SHA384_DIGEST_LENGTH
        case .SHA512:   result = CC_SHA512_DIGEST_LENGTH
        }
        return Int(result)
    }
}

extension String {
    /*
     *   func：加密方法
     *   参数1：加密方式； 参数2：加密的key
     */
    func hmac(algorithm: CryptoAlgorithm, key: String) -> String {
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = algorithm.digestLength
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        let keyStr = key.cString(using: String.Encoding.utf8)
        let keyLen = Int(key.lengthOfBytes(using: String.Encoding.utf8))
        
        CCHmac(algorithm.HMACAlgorithm, keyStr!, keyLen, str!, strLen, result)
        
        let digest = stringFromResult(result:  result, length: digestLen)
        
        result.deallocate()
        
        return digest
    }
    
    private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
        let hash = NSMutableString()
        for i in 0..<length {
            hash.appendFormat("%02x", result[i])
        }
        return String(hash)
    }
}

// MARK:======================================UUID========================================

func getUUID() -> String {
    
    if let uuid = UserDefaults.standard.value(forKey: "getUUID") {
        
        return uuid as! String
    } else {
        
        let uuid = UUID().uuidString
        UserDefaults.standard.setValue(uuid, forKey: "getUUID")
        UserDefaults.standard.synchronize()
        return uuid
    }
}

// MARK:======================================一些方法========================================

// 发送通知
func PostNotification(_ name: String) {
    
    NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: name), object: nil)

}
